import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, leaveStatue } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import LeaveDetail from './LeaveDetail';
import Detail from './Detail';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ personal_audited_documents, loading, global }) => ({
  personal_audited_documents,
  global,
  loading: loading.models.personal_audited_documents,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      personal_audited_documents: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        personal_audited_documents: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'personal_audited_documents/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'personal_audited_documents/changeLoaded',
          });
          dispatch({
            type: 'personal_audited_documents/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'personal_audited_documents/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'personal_audited_documents/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'personal_audited_documents/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      personal_audited_documents: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          <FormItem label="文件审批类型">
            {getFieldDecorator('type', {
              initialValue: searchParams.type,
            })(
              <Input style={{width:'120px'}}/>
            )}
          </FormItem>
          <FormItem label="审批状态">
            {getFieldDecorator('status', {
              initialValue: searchParams.status,
            })(
              <Select style={{ width: '150px' }}>
                {
                  [{ id: '', value: '全部' }, { id: '-1', value: '已取消' }
                    , { id: '1', value: '未提交' }
                    , { id: '2', value: '等待审批' }, { id: '4', value: '审批成功' }, {
                    id: '3',
                    value: '审批不通过',
                  }, { id: '5', value: '审批完成' }].map((item, index) => {
                    return <Option key={index} value={item.id}>{item.value}</Option>;
                  })
                }
              </Select>
            )}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'public_file_operation' }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              新建文件审批
            </Button>
          }
        </FormItem>

      </Form>
    );
  }
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      type:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    let formData = new FormData();
    let reviewers=[]
    for(let key in formValues){
      let splitKey=key.split('-')
      if(key.indexOf('staff_id')>=0){
        reviewers.push({
          id:formValues[key],
        })
      }

    }
    console.log('reviewers',reviewers)

    if(formValues.file){
      formData.append("attachments[]", formValues.file.file);
    }else{
      message.error('请选择文件')
      return false ;
    }
    formData.append("file_name", formValues.file_name);
    formData.append("file_type", formValues.file_type);
    formData.append("company_id", sessionStorage.getItem('company_id'));
    formData.append("issue_unit", formValues.issue_unit);
    formData.append("description", formValues.description);
    formData.append("issue_time", formValues.issue_time?moment(formValues.issue_time).format('YYYY-MM-DD'):'');
    reviewers.forEach((item,index) => {
      formData.append(`middlemen[${index}][id]`, item.id);
    })
    this.props.dispatch({
      type: 'personal_audited_documents/add',
      payload: formData,
      callback() {
        message.success('新建文件审批成功');
        that.setState({
          addModal: false,
        });
        const {
          personal_audited_documents: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    let formData = new FormData();
    let reviewers=[]
    for(let key in formValues){
      let splitKey=key.split('-')
      if(key.indexOf('staff_id')>=0){
        reviewers.push({
          id:formValues[key],
        })
      }

    }
    console.log('reviewers',reviewers)
    if(formValues.file){
      console.log('保存新文件')
      formData.append("attachments[]", formValues.file.file);
    }else if(this.state.editRecord.attachments.length>0){
      console.log('保存旧文件')
      formData.append("preserved_attachments[0][key]", this.state.editRecord.attachments[0].key);
    }else if(!formValues.file){
      message.error('请选择文件')
      return false ;
    }
    formData.append("file_name", formValues.file_name);
    formData.append("company_id", sessionStorage.getItem('company_id'));
    formData.append("file_type", formValues.file_type);
    formData.append("issue_unit", formValues.issue_unit);
    formData.append("description", formValues.description);
    formData.append("issue_time", formValues.issue_time?moment(formValues.issue_time).format('YYYY-MM-DD'):'');
    reviewers.forEach((item,index) => {
      formData.append(`middlemen[${index}][id]`, item.id);
    })
    this.props.dispatch({
      type: 'personal_audited_documents/edit',
      payload: {
        formData,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改文件审批成功');
        that.setState({
          editModal: false,
        });
        const {
          personal_audited_documents: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `personal_audited_documents/remove`,
      payload: { id },
      callback: () => {
        message.success('删除员工成功');
        const {
          personal_audited_documents: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleUpload=(type,id)=>{
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `personal_audited_documents/${type}`,
      payload: { id },
      callback: () => {
        message.success(`${type==='submit'?'提交':'取消'}文件审批成功`);
        const {
          personal_audited_documents: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  }
  render() {
    const that = this;
    const {
      personal_audited_documents: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            personal_audited_documents: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '创建时间',
        key: 'created_at',
        frozen: true,
        width: 150,
      },
      {
        name: '文件名称',
        key: 'file_name',
        frozen: true,
        width: 150,
      },
      {
        name: '文件类型',
        frozen: true,
        width: 123,
        key: 'file_type',
      },
      {
        name: '来文单位',
        frozen: true,
        width: 150,
        key: 'issue_unit',
      },

      {
        name: '来文时间',
        key: 'issue_time',
        width: 150,
      },
      {
        name: '文件说明',
        key: 'description',
        width: 150,
      },
      {
        name: '状态',
        key: 'status',
        width: 100,
        formatter: (event) => {
          return leaveStatue(event.value)
        },
      },
      {
        name: '中间人',
        width: 150,
        key: 'middlemen',
        formatter: (event) => {
          return event.value.map((item,index)=>{
            return `${item.name}、`
          })
        },
      },
      {
        name: '审批人',
        width: 150,
        key: 'reviewers',
        formatter: (event) => {
          return event.value.map((item,index)=>{
            return `${item.name}、`
          })
        },
      },
      {
        name: '操作',
        width: 380,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                detailModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            event.row.status===1&&
            <Button
              className={'btn-cyan'}
              type="primary"
              icon="edit"
              size="small"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  editModal: true,
                });
              }
              }
            >修改
            </Button>
          }
          {
            event.row.status===1&&<Button
              type="primary"
              icon="tool"
              size="small"
              onClick={(e) => {
                confirm({
                  title: `确定要提交进行审批吗?`,
                  content: '提交后不可再修改',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleUpload('submit',event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >提交审批
            </Button>
          }
          {
            event.row.status===1&&
            <Button
              type="danger"
              icon="delete"
              size="small"
              onClick={(e) => {
                confirm({
                  title: `确定要取消该文件审批吗?`,
                  content: '提交后不可再修改',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleUpload('cancel',event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >取消文件审批
            </Button>
          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>新建文件审批</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'personal_audited_documents/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal"
                                title={`新建文件审批`}/>}
        visible={this.state.addModal}
        centered
        className="addModal"
        width={1100}
        onOk={this.handleAdd}
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <Detail  wrappedComponentRef={(inst) => this.AddForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.detailModal} modalClass="detailModal"
                                title={`${this.state.editRecord.created_at} 文件审批详情`}/>}
        destroyOnClose
        visible={this.state.detailModal}
        centered
        className="detailModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={1100}
        onOk={() => {
          this.setState({ detailModal: false, editRecord: {} });
        }}
        onCancel={() => {
          this.setState({ detailModal: false, editRecord: {} });
        }}
      >
        <LeaveDetail editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`${this.state.editRecord.created_at} 编辑`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={1100}
        onOk={this.handleEdit}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}
      >
        <Detail editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
